package cz.af.portletExams.subjectExamsOverview.dto;

import cz.af.portletExams.model.Exam;
import cz.af.portletExams.model.ExamOverviewUser;
import org.joda.time.Days;
import org.joda.time.LocalDateTime;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DtoCreator {

    public static List<ExamForSubjectExamsView> createDtos(List<Exam> examsForSubject, List<String> examsForUser, ExamOverviewUser user) {
        if (examsForSubject.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        final String subjectId = examsForSubject.get(0).getSubjectId();

        final String customExamIdForSubject = user.getExams().get(subjectId);

        final List<ExamForSubjectExamsView> examsForSubjectExamsView = new ArrayList<ExamForSubjectExamsView>();
        for (Exam exam : examsForSubject) {
            final ExamForSubjectExamsView examForView = new ExamForSubjectExamsView();
            examForView.setExamId(exam.getId());

            final LocalDateTime examLocalDate = exam.getDate();
            examForView.setLocalDate(examLocalDate.toLocalDate());
            examForView.setLocalTime(examLocalDate.toLocalTime());

            final LocalDateTime now = LocalDateTime.now();
            final Integer dayDiff = Days.daysBetween(examLocalDate, now).getDays();
            examForView.setDayLeft(-dayDiff);
            examForView.setInPast(examLocalDate.isBefore(now));
            examForView.setOccupied(exam.getOccupied() + "/" + exam.getCapacity());
            final boolean registered;
            if (customExamIdForSubject == null) {
                registered = examsForUser.contains(exam.getId());
            } else {
                registered = exam.getId().equals(customExamIdForSubject);
            }
            examForView.setRegistered(registered);
            examForView.setRegistrationPossible(!registered && exam.getCapacity() > exam.getOccupied());
            examsForSubjectExamsView.add(examForView);
        }
        return examsForSubjectExamsView;
    }
}
